import re

from odoo import api, models


class ReportSbSinvReport(models.AbstractModel):
    _name = 'report.sb_sale.sb_sinv_report'
    _description = 'sb_sinv_report'

    @api.model
    def _get_report_values(self, docids, data=None):
        self.env.context = dict(self.env.context, lang='en_US')
        report = self.env['ir.actions.report']._get_report_from_name('sb_sale.sb_sinv_report')
        docs = self.env['account.move'].browse(docids)
        report_lines_list = []
        total_amount_list = []

        def prepare_report_lines(docs):
            report_lines = []
            total_amount = 0.0

            for doc in docs:
                only_service = all(line.product_id.detailed_type == 'service' for line in doc.invoice_line_ids)
                for line in doc.invoice_line_ids:
                    if only_service:
                        # 服務類發票行
                        amount = line.price_total
                        total_amount += amount
                        report_lines.append({
                            'po_no': line.s_po or '',
                            'description': line.s_pn,
                            'quantity': line.quantity,
                            'unit_price': 0,  # 不顯示單價
                            'start_cost': line.price_unit,  # 不顯示 start cost
                            'amount': amount,
                            'note': '',
                            'nre_invoice': True,
                            'hs': False
                        })
                    else:
                        hs = ''
                        if line.product_id.detailed_type != 'service':
                            sale_line = line.sale_line_ids[:1]
                            start_cost_amount = 0.0
                            ext_amount = 0.0

                            if sale_line:
                                sale_order = sale_line.order_id
                                nre_lines = sale_order.order_line.filtered(lambda l: l.product_template_id.name == 'NRE')
                                ext_lines = sale_order.order_line.filtered(lambda l: l.product_template_id.name == 'Additional Charge')
                                if nre_lines:
                                    nre_line = nre_lines[0]
                                    nre_invoice_lines = nre_line.invoice_lines.filtered(
                                        lambda inv_line: inv_line.move_id.move_type == 'out_invoice'
                                    )
                                    other_invoices = nre_invoice_lines.filtered(lambda inv_line: inv_line.move_id.id == doc.id)
                                    if other_invoices:
                                        start_cost_amount = nre_line.price_total
                                if ext_lines:
                                    ext_line = ext_lines[0]
                                    ext_invoice_lines = ext_line.invoice_lines.filtered(
                                        lambda inv_line: inv_line.move_id.move_type == 'out_invoice'
                                    )
                                    other_invoices = ext_invoice_lines.filtered(lambda inv_line: inv_line.move_id.id == doc.id)
                                    if other_invoices:
                                        ext_amount = ext_line.price_total
                            if line.product_id:
                                match = re.search(r'W(\d{2})L', line.product_id.name)
                                if match:
                                    result = int(match.group(1))
                                    if result:
                                        if result == 1:
                                            hs = '8534.0010'
                                        elif result == 2:
                                            hs = '8534.0020'
                                        else:
                                            hs = '8534.0030 '

                            amount = line.price_total + start_cost_amount + ext_amount
                            total_amount += amount
                            report_lines.append({
                                'po_no': line.s_po or '',
                                'description': line.s_pn if line.s_pn else line.name,
                                'quantity': line.quantity,
                                'unit_price': line.price_unit,
                                'start_cost': start_cost_amount,
                                'amount': amount,
                                'ext': ext_amount,
                                'note': '',
                                'nre_invoice': False,
                                'hs': hs
                            })
            return report_lines, total_amount

        for doc in docs:
            report_lines, total_amount = prepare_report_lines(doc)
            report_lines_list.append(report_lines)
            total_amount_list.append(total_amount)
        # 生成報告數據
        return {
            'doc_ids': docids,
            'doc_model': report.model,
            'docs': docs,
            'data': data,
            'report_lines_list': report_lines_list,
            'total_amount_list': total_amount_list,
        }
